package mju.cxf.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import mju.cxf.context.BaseContext;
import mju.cxf.entity.*;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import mju.cxf.service.BillService;
import mju.cxf.service.OrderService;
import mju.cxf.service.SalesService;
import mju.cxf.service.impl.IntegralServiceImpl;
import mju.cxf.service.impl.UserServiceImpl;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import mju.cxf.config.AlipayConfig;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@RestController
@RequestMapping("/user/api/alipay")
@Slf4j
public class IAlipayController {

    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";

    private static final String FORMAT = "json";

    private static final String CHARSET = "UTF-8";

    private static final String SIGN_TYPE= "RSA2";

    @Autowired
    private OrderService orderService;

    @Autowired
    private AlipayConfig alipayConfig;

    @Autowired
    private SalesService salesService;
    @Autowired
    private UserServiceImpl userServiceImpl;
    @Autowired
    private IntegralServiceImpl integralServiceImpl;
    @Autowired
    private BillService billService;


    @GetMapping("/pay/{id}")
    public void pay(@PathVariable("id") String id, HttpServletResponse response) throws Exception {
        //查询订单信息
        System.out.println(id);
        Order orderVO = orderService.sleectOrderNumber(id);
        //1.创建Client,通过SDK提供的Client,负责调用支付宝的api

        this.payNotify(orderVO.getNumber());
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, alipayConfig.getAppId(),alipayConfig.getAppPrivateKey(),FORMAT,CHARSET, alipayConfig.getAlipayPublicKey(),SIGN_TYPE);
        //2.创建request并设置request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); //发送请求的Request类
        System.out.println(orderVO.getProductId());
        System.out.println(alipayConfig.getNotifyUrl());
        request.setNotifyUrl(alipayConfig.getNotifyUrl());
        String orderIds = UUID.randomUUID().toString().replace("-", ""); //随机生成订单编号
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderVO.getNumber());//生成的订单标号
        bizContent.put("total_amount",orderVO.getAmount());//订单总金额
        bizContent.put("subject", orderVO.getProductId());
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");//固定配置
        request.setBizContent(bizContent.toString());
//        request.setReturnUrl("http://218.244.157.246:10086");//支付完成后自动跳转到本地页面的路径
//        //执行请求 拿到响应的结果。返回给浏览器
        String form = alipayClient.pageExecute(request).getBody(); // 调用sdk生成表单

        response.setContentType("text/html;charset=" + CHARSET);
        response.getWriter().write(form);//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }

    public synchronized void payNotify(String orderId) {
                // 更新订单状态，设置支付信息
                Order order = orderService.sleectOrderNumber(orderId);
                log.info(String.valueOf(order));
                order.setStatus(1);
                final int quantity = order.getQuantity();
                LambdaQueryWrapper<Sales> sqw=new LambdaQueryWrapper<>();
                sqw.eq(Sales::getState,2).eq(Sales::getSpecificationsId,order.getProductId()).orderByDesc(Sales::getEmpSalesId)
                        .orderByAsc(Sales::getKeyOutTime).last("limit "+quantity);
                List<Sales> salesList = salesService.list(sqw);
                salesList.forEach(sales->{
                    sales.setState(4);
                    sales.setOrderNumber(order.getNumber());  //获取出售对应的订单号
                    sales.setSalesTime(LocalDateTime.now());  //获取出售时间
                    //卖家增加信用积分
                    if (sales.getUserId() != null){
                        User user =userServiceImpl.getById(sales.getUserId());
                        Integral integral = Integral.builder().build();
                        final Integer credit = user.getCredit();
                        log.info("用户积分"+credit);
                        int setCredit;
                        if (credit <=97 && credit >=0){
                            setCredit=credit+3;

                        }else if(credit<=100 && credit>97){
                            setCredit=100;
                        }else{
                            setCredit=0;
                        }
                        if (setCredit!=0){
                            user.setCredit(setCredit);
                            integral.setTittle("卖家增加信用分");
                            integral.setUserId(sales.getUserId());//获取用户id
                            integral.setType(3);  //修改为增加
                            integral.setCreateTime(LocalDateTime.now()); //记录时间
                            integral.setNumber(3);   //记录增减积分
                            integralServiceImpl.save(integral); //添加到数据库内
                        }
                        //卖家金钱
                        Bill bill = Bill.builder()
                                .topic("订单预收款")
                                .type(1)
                                .balancesType(1)
                                .createTime(LocalDateTime.now())
                                .number(sales.getAmount())
                                .userId(sales.getUserId())
                                .build();
                        billService.save(bill);
                        user.setFreezeBalances(user.getFreezeBalances()+sales.getAmount());
                        userServiceImpl.updateById(user);
                    }
                });
                //买家增加信用积分
                if (order.getUserId() != null){
                    User user =userServiceImpl.getById(order.getUserId());
                    Integral integral = Integral.builder().build();
                    final Integer credit = user.getCredit();
                    log.info("用户积分"+credit);
                    int setCredit;
                    if (credit <=97 && credit>0){
                        setCredit=credit+3;

                    }else if(credit<100 && credit>97){
                        setCredit=100;
                    }else{
                        setCredit=0;
                    }
                    if (setCredit!=0){
                        user.setCredit(setCredit);
                        integral.setTittle("买家增加信用分");
                        integral.setUserId(order.getUserId());//获取用户id
                        integral.setType(credit>97?setCredit-credit:3);  //修改为增加
                        integral.setCreateTime(LocalDateTime.now()); //记录时间
                        integral.setNumber(3);   //记录增减积分
                        integralServiceImpl.save(integral); //添加到数据库内
                    }
                    Integral integral1 = Integral.builder().build();
                    user.setMember(user.getMember()+order.getAmount().intValue());
                    integral1.setTittle("买家增加会员积分");
                    integral1.setUserId(order.getUserId());//获取用户id
                    integral1.setType(2);  //修改为增加
                    integral1.setCreateTime(LocalDateTime.now()); //记录时间
                    integral1.setNumber(order.getAmount().intValue());   //记录增减积分
                    integralServiceImpl.save(integral1); //添加到数据库内
                    userServiceImpl.updateById(user);
                }
                salesService.updateBatchById(salesList);
                order.setPaymentTime(LocalDateTime.now()); //添加支付时间

                orderService.updateById(order);
                //买家账单
                Bill bill = Bill.builder()
                        .topic("订单支付")
                        .type(2)
                        .balancesType(3)
                        .createTime(LocalDateTime.now())
                        .number(order.getAmount())
                        .userId(order.getUserId())
                        .build();
                billService.save(bill);


    }
//    @PostMapping("/notify")
//    @Transactional(rollbackFor = Exception.class)
//    public void payNotify(HttpServletRequest request) throws Exception{
//        log.info("支付异步回调");
//        if(request.getParameter("trade_status").equals("TRADE_SUCCESS")){
//            Map<String,String> params = new HashMap<>();
//            Map<String,String[]> requestParams = request.getParameterMap();
//            for(String name:requestParams.keySet()){
//                params.put(name, request.getParameter(name));
//            }
//            String sign = params.get("sign");
//            String content = AlipaySignature.getSignCheckContentV1(params);
//            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, alipayConfig.getAlipayPublicKey(),"utf-8");
//            //支付宝验证
//            if(checkSignature){
//                String tradeNo = params.get("out_trade_no"); //订单编号
//                String gmtPayment = params.get("gmt_payment"); //支付时间
//                String alipayTradeNo = params.get("trade_no"); //支付宝交易编号
//
//                // 更新订单状态，设置支付信息
//                Order order = orderService.sleectOrderNumber(tradeNo);
//
//                order.setStatus(1);
//                final int quantity = order.getQuantity();
//                LambdaQueryWrapper<Sales> sqw=new LambdaQueryWrapper<>();
//                sqw.eq(Sales::getState,2).eq(Sales::getSpecificationsId,order.getProductId()).orderByDesc(Sales::getEmpSalesId)
//                        .orderByAsc(Sales::getKeyOutTime).last("limit "+quantity);
//                List<Sales> salesList = salesService.list(sqw);
//                salesList.forEach(sales->{
//                    sales.setState(4);
//                    sales.setOrderNumber(order.getNumber());  //获取出售对应的订单号
//                    sales.setSalesTime(LocalDateTime.now());  //获取出售时间
//                    //卖家增加信用积分
//                    if (sales.getUserId() != null){
//                        User user =userServiceImpl.getById(sales.getUserId());
//                        Integral integral = Integral.builder().build();
//                        final Integer credit = user.getCredit();
//                        log.info("用户积分"+credit);
//                        int setCredit;
//                        if (credit <=97 && credit >=0){
//                            setCredit=credit+3;
//
//                        }else if(credit<=100 && credit>97){
//                            setCredit=100;
//                        }else{
//                            setCredit=0;
//                        }
//                        if (setCredit!=0){
//                            user.setCredit(setCredit);
//                            integral.setTittle("卖家增加信用分");
//                            integral.setUserId(sales.getUserId());//获取用户id
//                            integral.setType(3);  //修改为增加
//                            integral.setCreateTime(LocalDateTime.now()); //记录时间
//                            integral.setNumber(3);   //记录增减积分
//                            integralServiceImpl.save(integral); //添加到数据库内
//                        }
//                        //卖家金钱
//                        Bill bill = Bill.builder()
//                                .topic("订单预收款")
//                                .type(1)
//                                .balancesType(1)
//                                .createTime(LocalDateTime.now())
//                                .number(sales.getAmount())
//                                .userId(sales.getUserId())
//                                .build();
//                        billService.save(bill);
//                        user.setFreezeBalances(user.getFreezeBalances()+sales.getAmount());
//                        userServiceImpl.updateById(user);
//                    }
//                });
//                //买家增加信用积分
//                if (order.getUserId() != null){
//                    User user =userServiceImpl.getById(order.getUserId());
//                    Integral integral = Integral.builder().build();
//                    final Integer credit = user.getCredit();
//                    log.info("用户积分"+credit);
//                    int setCredit;
//                    if (credit <=97 && credit>0){
//                        setCredit=credit+3;
//
//                    }else if(credit<100 && credit>97){
//                        setCredit=100;
//                    }else{
//                        setCredit=0;
//                    }
//                    if (setCredit!=0){
//                        user.setCredit(setCredit);
//                        integral.setTittle("买家增加信用分");
//                        integral.setUserId(order.getUserId());//获取用户id
//                        integral.setType(credit>97?setCredit-credit:3);  //修改为增加
//                        integral.setCreateTime(LocalDateTime.now()); //记录时间
//                        integral.setNumber(3);   //记录增减积分
//                        integralServiceImpl.save(integral); //添加到数据库内
//                    }
//                    Integral integral1 = Integral.builder().build();
//                    user.setMember(user.getMember()+order.getAmount().intValue());
//                    integral1.setTittle("买家增加会员积分");
//                    integral1.setUserId(order.getUserId());//获取用户id
//                    integral1.setType(3);  //修改为增加
//                    integral1.setCreateTime(LocalDateTime.now()); //记录时间
//                    integral1.setNumber(order.getAmount().intValue());   //记录增减积分
//                    integralServiceImpl.save(integral1); //添加到数据库内
//                    userServiceImpl.updateById(user);
//                }
//                salesService.updateBatchById(salesList);
//                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//                LocalDateTime paymentTime = LocalDateTime.parse(gmtPayment, formatter);
//                order.setPaymentTime(paymentTime); //添加支付时间
//                order.setCompletionTime(LocalDateTime.now());  //获取订单完成时间
//                orderService.updateById(order);
//                //买家账单
//                Bill bill = Bill.builder()
//                        .topic("订单支付")
//                        .type(2)
//                        .balancesType(3)
//                        .createTime(LocalDateTime.now())
//                        .number(order.getAmount())
//                        .userId(order.getUserId())
//                        .build();
//                billService.save(bill);
//            }
//
//        }
//    }
}
